package it.unina.lab.config;

import it.unina.lab.model.ModalityEvent;
import it.unina.lab.model.TriggerHL;
import it.unina.lab.patterns.fsm.Entity;
import it.unina.lab.patterns.fsm.Event;
import it.unina.lab.patterns.fsm.Guard;
import it.unina.lab.patterns.fsm.State;

import java.util.List;



public class TriggerGuard implements Guard {

	private TriggerHL trigger = null;
	private Logger logger = Logger.getLogger();
	
	
	public TriggerGuard(TriggerHL trig){
		if(trig != null)
			trigger = trig;
	}
	
	
	@Override
	public boolean accept(Event message, Entity entity, State state) {
		if (message.getData() instanceof ModalityEvent) {
			ModalityEvent evento = (ModalityEvent) message.getData();
			return(checkValueIsRight(evento));
				
		}
		else
			throw new RuntimeException("Evento ricevuto di tipologia sconosciuta: " + message.getClass());

	}
	
	
	
	private boolean checkValueIsRight(ModalityEvent evento){
		if(!trigger.getModality().equalsIgnoreCase(evento.getModality()))
			return false;
		
		if(!trigger.getVariables().containsKey(evento.getVariabile()))
			return false;
			
		List<Object> values_variable = trigger.getVariables().get(evento.getVariabile());
		for(Object value : values_variable){
			if(value instanceof String){
				String string_value = (String) value;
				if(string_value.equalsIgnoreCase(evento.getValue_variabile())){
					logger.info("TriggerOK: " + trigger.getName());
					return true;
				}	
			}	
 		}
		
		return false;
	}

}
